package sales

import (
	"LogisticsPort/model"
	"LogisticsPort/sql"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

/*进货*/
func stock(r *gin.RouterGroup) {
	stock := r.Group("/stock")
	{
		stock.GET(sql.RequestList, stockList)
	}
}

func stockList(c *gin.Context) {
	sql.HttpHandle(sql.GET, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var list []model.PurchaseProduct
		db = db.Model(&list).
			Not("purchase_product.warehousing_time", "0000-00-00").
			Where("purchase_product.delivery_time", "0000-00-00").
			Select("purchase_product.*,product.factory_no,product.product_name").
			Joins("left join product on purchase_product.product_id = product.id").
			Preload("FuturesFee").
			Scan(&list)
		return db, list
	})
}

func stockAdd(c *gin.Context) {
	sql.HttpHandle(sql.ADD, c, func(db *gorm.DB) (*gorm.DB, interface{}) {
		var id = c.Query("id")
		var bean model.PurchaseProduct
		db.Where("purchase_product.id = ?", id).
			Select("purchase_product.*,product.factory_no,product.product_name").
			Joins("left join product on purchase_product.product_id = product.id").
			Scan(&bean)
		if db.RowsAffected == 0 {
			db.Error = errors.New(sql.ErrorUnExists)
			return db, nil
		}
		var inventory = model.Inventory{
			FactoryNo:       bean.FactoryNo,
			ProductName:     bean.ProductName,
			ContainerNo:     bean.ContainerNo,
			ContractNo:      bean.ContractNo,
			InventoryNumber: bean.ProductNumber,
			InventoryWeight: bean.ProductWeight,
		}
		return db, inventory
	})
}
